package cn.xiaoniu.day01;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.fastjson.JSON;

import cn.xiaoniu.day01.bean.RatingBean;
import cn.xiaoniu.day01.util.SortUtil;

/**
 * 1:读取数据
 * 2：数据的解析
 * 3：分组（把相同的数据（key相同）放到一起）   ----> 放进map中实现的
 * 4：局部排序
 * 5：取topn   ----->保存topn数据
 * @author root
 *
 */

public class TestMain1 {
	public static void main(String[] args) {
		Map<String, List<RatingBean>> map = getMap();
		//System.out.println(map.size());//最好能遍历的查看下数据
		Set<Entry<String,List<RatingBean>>> entrySet = map.entrySet();
		for (Entry<String, List<RatingBean>> entry : entrySet) {
			List<RatingBean> value = entry.getValue();//得到每个用户的评分数据集合
			String key = entry.getKey();
			//排序
			SortUtil.sortByRate(value);
			//取topn
			System.out.println(key);
			
			for (int i = 0; i <Math.min(20, value.size()); i++) {
				RatingBean ratingBean = value.get(i);
				System.out.println(ratingBean);
			}
			/*int sum = 0;
			for (RatingBean ratingBean : value) {
				if(sum<20){
					sum++;
					System.out.println(ratingBean);
				}else{
					break;
				}
			}*/
		}
	}

	public static Map<String, List<RatingBean>> getMap() {
		Map<String, List<RatingBean>> map = new HashMap<>();
		//1：读取数据
		try (BufferedReader br = new BufferedReader(new FileReader("D:\\data\\rating.json"));){
			String line = null;
			while((line=br.readLine())!=null){
				//System.out.println(line);
				RatingBean ratingBean = JSON.parseObject(line, RatingBean.class);
				if(map.containsKey(ratingBean.getUid())){//有值的情况
					List<RatingBean> list = map.get(ratingBean.getUid());//现有的list
					list.add(ratingBean);
					//map.put(ratingBean.getUid(), list);   可有可无的
				}else{//key是第一次出现的情况
					List<RatingBean> list = new ArrayList<>();
					list.add(ratingBean);
					map.put(ratingBean.getUid(), list);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

}
